#include "../header/common.h"

SDL_AudioSpec spec;
Uint32 sound_len;
Uint8 *sound_buffer;
int sound_pos;

void Callback (void *userdata, Uint8 *stream, int len)
{
 Uint8 *waveptr;
 if (sound_pos + len > sound_len)
 {
   return;
 }
 waveptr = sound_buffer + sound_pos;
 SDL_MixAudio(stream, waveptr, len, SDL_MIX_MAXVOLUME);
 sound_pos += len;
}

void play (int mode)
{
  switch(mode)
    {
    case 0:
      SDL_CloseAudio();
      SDL_FreeWAV (sound_buffer);
      break;
    case 1:
      SDL_CloseAudio();
      sound_pos=0;
      if (SDL_LoadWAV ("sound/background.wav", &spec, &sound_buffer, &sound_len) == NULL)
	exit (-1);
      spec.callback = Callback;
      if (SDL_OpenAudio (&spec, NULL) < 0)
	{
	  printf ("Kann audio nicht öffnen: %s\n", SDL_GetError ());
	  exit (-1);
	}
      SDL_PauseAudio (0);
      break;
    case 2:
      SDL_CloseAudio();
      sound_pos=0;
      if (SDL_LoadWAV ("sound/menubackground.wav", &spec, &sound_buffer, &sound_len) == NULL)
	exit (-1);
      spec.callback = Callback;
      if (SDL_OpenAudio (&spec, NULL) < 0)
	{
	  printf ("Kann audio nicht öffnen: %s\n", SDL_GetError ());
	  exit (-1);
	}
      SDL_PauseAudio (0);
      break;
    case 3:
      SDL_CloseAudio();
      sound_pos=0;
      if (SDL_LoadWAV ("sound/go.wav", &spec, &sound_buffer, &sound_len) == NULL)
	exit (-1);
      spec.callback = Callback;
      SDL_PauseAudio (0);
      break;
    }
}
